//
//  LouMusicPlayer.m
//  WXMusic
//
//  Created by 漫步人生路 on 15/9/7.
//  Copyright (c) 2015年 漫步人生路. All rights reserved.
//

#import "LouMusicPlayer.h"

@implementation LouMusicPlayer
{
    float songProgress;
    NSTimer *timer;
}
static LouMusicPlayer *louPlayer;
+ (LouMusicPlayer *)shareMusicPlayer
{
    if (louPlayer == nil) {
        louPlayer = [[LouMusicPlayer alloc]init];
    }
    return louPlayer;
}
- (AVPlayer *)louPlayer
{
    if (!_louPlayer) {
        _louPlayer = [[AVPlayer alloc]init];
    }
    return _louPlayer;
}

- (void)playSongWithUrl:(NSString *)url
{
    //如果item存在，那我们就先将观察者移除掉
    if (self.louPlayerItem) {
        [self.louPlayerItem removeObserver:self forKeyPath:@"status"];
    }
    //根据歌曲的url来获取歌曲的所有资源
    self.louPlayerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    /**
     *  给item添加一个观察者
     */
    [self.louPlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];
    //将item当中的所有资源替换成最新的
    [self.louPlayer replaceCurrentItemWithPlayerItem:self.louPlayerItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playNextSong) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [[NSMutableArray alloc]init];
    }
    return _modelArray;
}
- (void)reloadSong
{

    NSString *url = [[kPlayUrl stringByAppendingString:[self.modelArray objectAtIndex:self.index]] stringByAppendingString:kSongid];
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        self.playModel = [PlayModel shareJsonWithBitrate:dic[@"bitrate"] songInfo:dic[@"songinfo"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:nil];
        
        [self playSongWithUrl:self.playModel.file_link];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)playNextSong
{
    self.index += 1;
    if (self.index == self.modelArray.count - 1) {
        self.index = 0;
    }
    [self reloadSong];
    
}
//实现观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //根据字典内的新值来进行判断 integerValue会将值转换类型，根据我们的选择条件来进行执行其对应的方法
    NSLog(@"%@",change.allKeys);
    switch ([change[@"new"] integerValue]) {
        case AVPlayerItemStatusFailed:
            NSLog(@"缓冲失败");
            break;
        case AVPlayerStatusReadyToPlay:
            NSLog(@"缓冲成功");
            self.readyToPlay = YES;
            //创建一个通知发送一条消息告知可以播放
            [[NSNotificationCenter defaultCenter] postNotificationName:@"readyToPlay" object:nil];
            break;
        case AVPlayerStatusUnknown:
            NSLog(@"状态未知");
            break;
        default:
            break;
    }
}

- (void)starPlaySong
{
    //如果缓冲成功，开始播放
    if (self.readyToPlay == YES) {
        [self.louPlayer play];
        self.isPlaying = YES;
      timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(sliderRun) userInfo:nil repeats:YES];
    }
}
- (void)stopPlaySong
{
    [self.louPlayer pause];
    self.isPlaying = NO;
    [timer invalidate];
    timer = nil;
}
//指定位置播放
- (void)seekToTime:(CGFloat)time
{
    if (self.isPlaying == YES) {
        //正在播放
        [self stopPlaySong];
        [self.louPlayer seekToTime:CMTimeMakeWithSeconds(time, self.louPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self starPlaySong];
        }];
    }
    else
    {
        //暂停状态
        [self.louPlayer seekToTime:CMTimeMakeWithSeconds(time, self.louPlayer.currentTime.timescale) completionHandler:nil];
    }
}
- (void)sliderRun
{
     songProgress = self.louPlayer.currentTime.value / self.louPlayer.currentTime.timescale;
    //将我们运行时间传进参数给ViewController使用
    [self.louPlayerDelegate audioManagerStreamer:self songProgress:songProgress];
}



@end
